package com.laike.pay.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.laike.pay.R;
import com.laike.pay.adapter.BrushAdapter;
import com.laike.pay.base.BaseActivity;
import com.laike.pay.bean.PayOrder;
import com.laike.pay.greendao.PayOrderDao;
import com.laike.pay.http.BaseCallback;
import com.laike.pay.http.HttpRetrofit;
import com.laike.pay.http.ParamsUtils;
import com.laike.pay.http.Result;
import com.laike.pay.http.api.ApiName;
import com.laike.pay.http.api.SerivceApi;
import com.laike.pay.qrdecode.CodeUtils;
import com.laike.pay.qrdecode.MipcaActivityCapture;
import com.laike.pay.utils.GreenDaoManager;
import com.laike.pay.utils.ProgressDialogUtils;
import com.laike.pay.utils.SharedPreferencesUtils;
import com.laike.pay.utils.ToastUtils;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Response;


public class BrushCardActivity extends BaseActivity implements
        BaseCallback<Result<PayOrder>>, EasyPermissions.PermissionCallbacks, View.OnClickListener {
    private final int REQUEST_CODE = 100;
    private final int CAMERA_CODE = 0;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.text)
    TextView text;
    @Bind(R.id.gridView)
    GridView gridView;
    @Bind(R.id.value)
    TextView value;
    @Bind(R.id.collect_money_btn)
    TextView collectMoneyBtn; //收款按钮
    private BrushAdapter brushAdapter = null;
    private double price = 0;
    private Map<String, String> params;
    protected String appidStr = "";
    protected String terminalNumber = "";
    private boolean isPlaySpeak = false;
    /**
     * 讯飞语音播报
     */
    private static String TAG = BrushCardActivity.class.getSimpleName();
    // 语音合成对象
    private SpeechSynthesizer mTts;
    // 默认发音人
    private String voicer = "xiaoyan";
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    protected int type = 0;
    public int typeValue = 0;
    private PayOrderDao payOrderDao = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public int getContentViewResId() {
        return R.layout.activity_brush_card;
    }

    @Override
    public void intiViews() {
        initViews();
    }

    @Override
    public String setTitle() {
        return null;
    }

    @Override
    public void onAttachedToWindow() {
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
        super.onAttachedToWindow();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            Intent intent = new Intent(this, CollectMoneyActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initViews() {
        appidStr = SharedPreferencesUtils.getAppid();
        terminalNumber = SharedPreferencesUtils.getTerminalNumber();
        isPlaySpeak = SharedPreferencesUtils.getPlaySpeak().equals("1");
        intiTts();
        Intent intent = getIntent();
        if (null != intent) {
            type = intent.getIntExtra("type", 0);
            typeValue = intent.getIntExtra("value", 0);
        }
        back.setOnClickListener(this);
        collectMoneyBtn.setOnClickListener(this);
        brushAdapter = new BrushAdapter(this);
        gridView.setAdapter(brushAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int num = (int) brushAdapter.getItem(i);
                changeValue(num);
            }
        });
        value.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().equals("0.00")) {
                    point = false;
                    zero = false;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    /**
     * 初始化语音播报
     */
    private void intiTts() {
        mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);
        setParam();
    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Log.d(TAG, "init data fail，errorCode message = " + code);
            }
        }
    };

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
        }

        @Override
        public void onSpeakPaused() {
        }

        @Override
        public void onSpeakResumed() {
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                Log.d(TAG, "play onCompleted");
            } else if (error != null) {
                Log.d(TAG, "play onCompleted：" + error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
        }
    };

    /**
     * 参数设置
     *
     * @return
     */
    private void setParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, "10");
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, "50");
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME, "100");
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
    }


    private boolean point = false;//用来控制点".",示例"xx.xx"
    private boolean zero = false;//用来控制点"." 之后的小数,示例"xx.0x"

    @SuppressLint("SetTextI18n")
    private void changeValue(int num) {
        String str = value.getText().toString();
        String number = str.substring(0, str.indexOf("."));
        String number1 = str.substring(str.indexOf(".") + 1, str.length());
        int temp = Integer.parseInt(number1);
        switch (num) {
            case 0:
                if (!str.equals("0.00")) {
                    if (!point) {
                        value.setText(number + num + "." + number1);
                    } else if (temp < 10 && temp % 10 == 0) {
                        value.setText(number + "." + "0" + num);
                        zero = true;
                    }
                }
                if (point) {
                    zero = true;
                }
                break;
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
                if (!point) {
                    value.setText((number.equals("0") ? "" : number) + num + "." + number1);
                } else {
                    if (temp == 0) {
                        if (zero) {
                            value.setText((number.equals("0") ? "0" : number) + "." + "0" + num);
                        } else {
                            value.setText((number.equals("0") ? "0" : number) + "." + num + "0");
                        }
                    } else if (temp >= 10 && temp % 10 == 0) {
                        value.setText((number.equals("0") ? "0" : number) + "." + number1.substring(0, 1) + num);
                    }
                }
                break;
            case 10://代表"."
                point = true;
                break;
            case 11://代表"回删"
                //表示没有小数点
                if (!str.equals("0.00")) {
                    if (temp == 0) {
                        String integer = number.substring(0, number.length() - 1).equals("") ? "0" : number.substring(0, number.length() - 1);
                        value.setText(integer + "." + number1);
                        point = false;
                    } else if (temp % 10 == 0) {
                        value.setText(number + "." + "00");
                        point = false;
                        zero = false;
                    } else if (temp % 10 != 0) {
                        value.setText(number + "." + number1.substring(0, 1) + "0");
                    }
                }
                break;
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.back:
                this.finish();
                break;
            case R.id.collect_money_btn:
                if (type == -1) {
                    //刷卡
                    getOrderId();
                } else {
                    // 跳转道扫码
                    if (coollectMoney()) {
                        String[] perms = {Manifest.permission.CAMERA};
                        if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
                            Intent qrIntent = new Intent(this, MipcaActivityCapture.class);
                            qrIntent.putExtra("type", 200);
                            qrIntent.putExtra("title", getString(R.string.sweep_collect_money));
                            startActivityForResult(qrIntent, REQUEST_CODE);
                        } else {
                            EasyPermissions.requestPermissions(this, getString(R.string.get_permissions_tips), CAMERA_CODE, perms);
                        }
                    }
                }
                break;
        }
    }

    public void getOrderId() {

    }

    @Override
    protected void onDestroy() {
        point = false;
        zero = false;
        super.onDestroy();
        if (null != mTts) {
            mTts.stopSpeaking();
            // 退出时释放连接
            mTts.destroy();
        }
    }

    @Override
    protected void onResume() {
        //移动数据统计分析
        FlowerCollector.onResume(this);
        FlowerCollector.onPageStart(TAG);
        super.onResume();
    }

    @Override
    protected void onPause() {
        //移动数据统计分析
        FlowerCollector.onPageEnd(TAG);
        FlowerCollector.onPause(this);
        super.onPause();
    }

    /**
     * 收款逻辑判断
     *
     * @return
     */
    protected boolean coollectMoney() {
        String sum = value.getText().toString();
        if (sum.equals("0.00")) {
            ToastUtils.showToast(this, R.string.jine_tips);
            return false;
        }
        Double su = new BigDecimal(sum).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
        price = su;
        return true;
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        switch (requestCode) {
            case CAMERA_CODE:
                Intent intent = new Intent(this, MipcaActivityCapture.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        switch (requestCode) {
            case CAMERA_CODE:
                Toast.makeText(this, R.string.get_permissions_fails, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    ProgressDialogUtils.showProgress(this, R.string.common_loading);
                    params = new HashMap<>();
                    params.put("method", ApiName.PAY_MENT);
                    params.put("total_amount", price + "");
                    params.put("auth_code", result);
                    HttpRetrofit.getInstance().getInterfaceApi(SerivceApi.class).payMent(price + "", result, appidStr, ApiName.PAY_MENT
                            , terminalNumber, ParamsUtils.getParams(result, price + "")).enqueue(this);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    @Override
    public void onResponse(Call<Result<PayOrder>> call, Response<Result<PayOrder>> response) {
        ProgressDialogUtils.dismissProgress();
        if (response.code() == 200) {//请求发送成功
            if (response.body().getStatus().equals("1")) {//服务器返回状态1：成功，0：失败
                PayOrder order = response.body().getResult();
                if (order.getStatus().equals("0")) {
                    ToastUtils.showToast(this, getString(R.string.no_pay), 3000);
                    return;
                }
                if (order != null) {
                    payOrderDao = GreenDaoManager.getInstance().getNewSession().getPayOrderDao();
                    long i = payOrderDao.insert(order);
                }
                //重置收款金额
                reset();
                ToastUtils.showToast(this, response.body().getInfo(), 5000);
                if (isPlaySpeak) {
                    // 移动数据分析，收集开始合成事件
                    FlowerCollector.onEvent(this, "tts_play");
                    mTts.startSpeaking(getString(R.string.text_to_speak_tips, order.getPay_amount()), mTtsListener);
                }
                Intent intent = new Intent(this, DealDetailsActivity.class);
                intent.putExtra("type", 200);
                intent.putExtra("order", order);
                startActivity(intent);
            } else {
                ToastUtils.showToast(this, getString(R.string.collect_money_fail, response.body().getInfo()));
            }
        }
    }

    protected void reset() {
        value.setText("0.00");
        point = false;
        zero = false;
    }

    @Override
    public void onFailure(Call<Result<PayOrder>> call, Throwable t) {
        ProgressDialogUtils.dismissProgress();
        Log.v("onFailure", "----" + t.getMessage());
    }

}
